<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人     
 * Date: 2015-09-09
 */
namespace Admin\Controller;
use Admin\Logic\GoodsLogic;
use Think\AjaxPage;
use Think\Page;
use Think\Controller;

class GoodsController extends Controller {
    
    /**
     *  商品分类列表
     */
    public function categoryList(){                
        $GoodsLogic = new GoodsLogic();               
        $cat_list = $GoodsLogic->goods_cat_list();
        $goods_type = M('goods_type')->getField('id,name');
        $this->assign('goods_type',$goods_type);
        $this->assign('cat_list',$cat_list);  
        $this->display();        
    }
    
    /**
     * 添加修改商品分类
     * 手动拷贝分类正则 ([\u4e00-\u9fa5/\w]+)  ('393','$1'), 
     * select * from tp_goods_category where id = 393
        select * from tp_goods_category where parent_id = 393
        update tp_goods_category  set parent_id_path = concat_ws('_','0_76_393',id),`level` = 3 where parent_id = 393
        insert into `tp_goods_category` (`parent_id`,`name`) values 
        ('393','时尚饰品'),
     */
    public function addEditCategory(){
        
            $GoodsLogic = new GoodsLogic();       
            $db_prefix = C('DB_PREFIX');
            $GoodsCategory = D('GoodsCategory');
            $post_data  =   $this->verific(encryptDecrypt(C('KEY_ERP'),$_POST['data'],1),1);

            if($post_data['is_change'] == 1)
            {

                $goods_category_info = $GoodsCategory->where(array('cate_id'=>$post_data['cate_id']))->find();
                if(!$goods_category_info){
                    //  编辑
                    $return_arr = array(
                        'status' => -1,
                        'msg'   => '暂无信息!',
                        'data'  => '',
                    );
                    _json($return_arr);
                }
                $post_data['parent_id_path']    =   implode('_',explode(',',$post_data['parent_id_path']));
                unset($post_data['is_change']);
                $update_result = $GoodsCategory->where(array('cate_id'=>$goods_category_info['cate_id']))->save($post_data);
                if($update_result !== false){
                    $return_arr = array(
                        'status' => 200,
                        'msg'   => '修改成功',
                        'data'  => '',
                    );
                    _json($return_arr);          
                }
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '修改失败',
                    'data'  => '',
                );
                _json($return_arr);
            }else{
                $post_data['parent_id_path']    =   implode('_',explode(',',$post_data['parent_id_path']));
                unset($post_data['is_change']);
                $update_result = $GoodsCategory->add($post_data);
                if($update_result){
                    $return_arr = array(
                        'status' => 200,
                        'msg'   => '修改成功',
                        'data'  => '',
                    );
                    _json($return_arr);          
                }
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '修改失败',
                    'data'  => '',
                );
                _json($return_arr);
            }


    }
    
    /**
     * 删除分类
     */
    public function delGoodsCategory(){
        $GoodsCategory = D('GoodsCategory');
        $post_data  =   encryptDecrypt(C('KEY_ERP'),$_POST['data'],1);
        // 删除分类
        $GoodsCategory->where("cate_id = {$post_data['cate_id']}")->delete();   
        $return_arr = array(
            'status' => 200,
            'msg'   => '操作成功',
            'data'  => '',
        );
        _json($return_arr);
    }
    
    
    /**
     *  商品列表
     */
    public function goodsList(){      
        $GoodsLogic = new GoodsLogic();        
        $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $this->display();                                           
    }
    
    /**
     *  商品列表
     */
    public function ajaxGoodsList(){            
        
        $where = ' 1 = 1 '; // 搜索条件                
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;        
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('goods_state') !== '') && $where = "$where and goods_state = ".I('goods_state') ;                
        $cat_id = I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        
        if($cat_id > 0)
        {            
            $where .= " and (cat_id1 = $cat_id or cat_id2 = $cat_id or cat_id3 = $cat_id ) "; // 初始化搜索条件
        }        
        $where.="and store_id='0'";
        $a=session();
        $admin=$a['admin_id'];
        $role=M('admin')->where("admin_id=$admin")->find();
        $role_id=$role['role_id'];
        $where.="and roleid=$role_id";
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        /**  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        */
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $goods_state = C('goods_state');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('goods_state',$goods_state);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }    
    
    
    /**
     * 添加修改商品
     */
    public function addEditGoods(){
            $Goods = D('Goods');
            $post_data  =   $this->verific(encryptDecrypt(C('KEY_ERP'),$_POST['data'],1),2);

            if($post_data['is_change'] == 1)
            {

                $goods_info =$Goods->where(array('goods_name'=>$post_data['goods_name']))->select();
                if(!$goods_info){
                    //  编辑
                    $return_arr = array(
                        'status' => -1,
                        'msg'   => '暂无信息!',
                        'data'  => '',
                    );
                    _json($return_arr);
                }
                $data['goods_name'] =   $post_data['goods_name'];
                $data['cat_id1'] =   $post_data['cat_id1'];
                $data['cat_id2'] =   $post_data['cat_id2'];
                $data['cat_id3'] =   $post_data['cat_id3'];
                $data['good_cishu']   =   $post_data['cishu'];
                $data['shop_price']   =   $post_data['shop_price'];
                $data['market_price']   =   $post_data['shop_price'];
                foreach ($post_data['location_data'] as $key => $value) {
                    //var_dump($value);
                    //$data['goods_sn'] =   $value['goods_sn'];
                    $data['roleid'] =   $value['roleid'];
                    $data['store_id'] =   $value['store_id'];
                    $data['store_count']    =   $value['store_count'];
                    $update_result = $Goods->where(array('goods_sn'=>$value['goods_sn']))->save($data);

                }
                $return_arr = array(
                    'status' => 200,
                    'msg'   => '修改成功',
                    'data'  => '',
                );
                _json($return_arr);   

            }else{
                $data['shop_price']   =   $post_data['shop_price'];
                $data['market_price']   =   $post_data['shop_price'];
                $data['goods_name'] =   $post_data['goods_name'];
                $data['cat_id1'] =   $post_data['cat_id1'];
                $data['cat_id2'] =   $post_data['cat_id2'];
                $data['cat_id3'] =   $post_data['cat_id3'];
                $data['good_cishu']   =   $post_data['cishu'];

                foreach ($post_data['location_data'] as $key => $value) {
                    //var_dump($value);
                    $data['goods_sn'] =   $value['goods_sn'];
                    $data['roleid'] =   $value['roleid'];
                    $data['store_id'] =   $value['store_id'];
                    $data['store_count']    =   $value['store_count'];

                    $update_result = $Goods->add($data);
                }
                $return_arr = array(
                    'status' => 200,
                    'msg'   => '添加成功',
                    'data'  => '',
                );
                _json($return_arr);          

            }                                    
    }             
    /**
     * 删除商品
     */
    public function delGoods()
    {
        $Goods = D('Goods');
        $post_data  =   encryptDecrypt(C('KEY_ERP'),$_POST['data'],2);
        // 删除分类
        $Goods->where("goods_sn = {$post_data['goods_sn']}")->delete();   
        $return_arr = array(
            'status' => 200,
            'msg'   => '操作成功',
            'data'  => '',
        );
        _json($return_arr);
    }   
    
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }    
   


    /**
     * 商品批量操作
     */
    public function act()
    {
        $act = I('post.act', '');
        $goods_ids = I('post.goods_ids');
        $goods_state = I('post.goods_state');
        $reason = I('post.reason');

        $return_success = array('status' => 1, 'msg' => '操作成功', 'data' => '');
        if ($act == 'hot') {
            $hot_condition['goods_id'] = array('in', $goods_ids);
            M('goods')->where($hot_condition)->save(array('is_hot' => 1));
            $this->ajaxReturn($return_success);
        }
        if ($act == 'recommend') {
            $recommend_condition['goods_id'] = array('in', $goods_ids);
            M('goods')->where($recommend_condition)->save(array('is_recommend' => 1));
            $this->ajaxReturn($return_success);
        }
        if ($act == 'new') {
            $new_condition['goods_id'] = array('in', $goods_ids);
            M('goods')->where($new_condition)->save(array('is_new' => 1));
            $this->ajaxReturn($return_success);
        }
        if ($act = 'examine') {
            $goods_array = explode(',', $goods_ids);
            $goods_state_cg = C('goods_state');
            if (!array_key_exists($goods_state, $goods_state_cg)) {
                $return_success = array('status' => -1, 'msg' => '操作失败，商品没有这种属性', 'data' => '');
                $this->ajaxReturn($return_success);
            }
            foreach ($goods_array as $key => $val) {
                $update_goods_state = M('goods')->where("goods_id = $val")->save(array('goods_state' => $goods_state));
                if ($update_goods_state) {
                    $update_goods = M('goods')->where(array('goods_id' => $val))->find();
                    // 给商家发站内消息 告诉商家商品被批量操作
                    $store_msg = array(
                        'store_id' => $update_goods['store_id'],
                        'content' => "您的商品\"{$update_goods[goods_name]}\"被{$goods_state_cg[$goods_state]},原因:{$reason}",
                        'addtime' => time(),
                    );
                    M('store_msg')->add($store_msg);
                }
            }
            $this->ajaxReturn($return_success);
        }
        $return_fail = array('status' => -1, 'msg' => '没有找到该批量操作', 'data' => '');
        $this->ajaxReturn($return_fail);
    }
    /**
     * [verific 验证数据]
     * @param  [type] $data [date数据]
     * @return [type] $type [验证类型]
     */
    public function verific($data,$type){
        if($type == 1){
            if(!$data['name'])  _json(array('status'=>-1,'msg'=>'分类名称不能为空','data'=>''));
            if(!$data['cate_id'])  _json(array('status'=>-1,'msg'=>'分类名称不能为空','data'=>''));
            return $data;
        }elseif($type == 2){
            //  if(!$data['goods_sn'])  _json(array('status'=>-1,'msg'=>'商品编号不能为空','data'=>''));
            if(!$data['goods_name'])  _json(array('status'=>-1,'msg'=>'商品名称不能为空','data'=>''));
            return $data;
        }
    }
}